<template>
  <div class="customer-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>客户管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增客户
      </el-button>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable />
        </el-form-item>
        <el-form-item label="客户类型">
          <el-select v-model="searchForm.customerType" placeholder="请选择客户类型" clearable>
            <el-option label="企业客户" value="enterprise" />
            <el-option label="个人客户" value="individual" />
            <el-option label="政府机构" value="government" />
            <el-option label="非营利组织" value="nonprofit" />
          </el-select>
        </el-form-item>
        <el-form-item label="信用等级">
          <el-select v-model="searchForm.creditLevel" placeholder="请选择信用等级" clearable>
            <el-option label="AAA" value="AAA" />
            <el-option label="AA" value="AA" />
            <el-option label="A" value="A" />
            <el-option label="BBB" value="BBB" />
            <el-option label="BB" value="BB" />
            <el-option label="B" value="B" />
            <el-option label="C" value="C" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" value="active" />
            <el-option label="暂停" value="suspended" />
            <el-option label="黑名单" value="blacklist" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在地区">
          <el-input v-model="searchForm.region" placeholder="请输入地区" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="customerCode" label="客户编码" width="120" fixed="left" />
        <el-table-column prop="customerName" label="客户名称" width="200" />
        <el-table-column prop="customerType" label="客户类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getCustomerTypeColor(row.customerType)" size="small">
              {{ getCustomerTypeText(row.customerType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contactPerson" label="联系人" width="100" />
        <el-table-column prop="contactPhone" label="联系电话" width="130" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="region" label="所在地区" width="120" />
        <el-table-column prop="creditLevel" label="信用等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getCreditLevelColor(row.creditLevel)" size="small">
              {{ row.creditLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creditLimit" label="信用额度" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.creditLimit?.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalOrders" label="订单总数" width="100" align="center" />
        <el-table-column prop="totalAmount" label="累计金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.totalAmount?.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-dropdown @command="handleCommand">
              <el-button type="info" size="small">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{action: 'suspend', row}" v-if="row.status === 'active'">
                    暂停合作
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'activate', row}" v-if="row.status === 'suspended'">
                    恢复合作
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'blacklist', row}" v-if="row.status !== 'blacklist'">
                    加入黑名单
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'credit', row}">
                    调整信用
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'orders', row}">
                    查看订单
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="customer-form"
      >
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户名称" prop="customerName">
                  <el-input v-model="formData.customerName" placeholder="请输入客户名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户类型" prop="customerType">
                  <el-select v-model="formData.customerType" placeholder="请选择客户类型">
                    <el-option label="企业客户" value="enterprise" />
                    <el-option label="个人客户" value="individual" />
                    <el-option label="政府机构" value="government" />
                    <el-option label="非营利组织" value="nonprofit" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系人" prop="contactPerson">
                  <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="formData.email" placeholder="请输入邮箱" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="传真">
                  <el-input v-model="formData.fax" placeholder="请输入传真" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="所在地区" prop="region">
                  <el-input v-model="formData.region" placeholder="请输入所在地区" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="详细地址">
                  <el-input v-model="formData.address" placeholder="请输入详细地址" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <el-tab-pane label="信用信息" name="credit">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="信用等级" prop="creditLevel">
                  <el-select v-model="formData.creditLevel" placeholder="请选择信用等级">
                    <el-option label="AAA" value="AAA" />
                    <el-option label="AA" value="AA" />
                    <el-option label="A" value="A" />
                    <el-option label="BBB" value="BBB" />
                    <el-option label="BB" value="BB" />
                    <el-option label="B" value="B" />
                    <el-option label="C" value="C" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="信用额度" prop="creditLimit">
                  <el-input-number
                    v-model="formData.creditLimit"
                    :min="0"
                    :precision="2"
                    placeholder="请输入信用额度"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="付款方式">
                  <el-select v-model="formData.paymentMethod" placeholder="请选择付款方式">
                    <el-option label="现金" value="cash" />
                    <el-option label="银行转账" value="transfer" />
                    <el-option label="支票" value="check" />
                    <el-option label="信用证" value="credit" />
                    <el-option label="月结" value="monthly" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="账期天数">
                  <el-input-number
                    v-model="formData.paymentDays"
                    :min="0"
                    :max="365"
                    placeholder="请输入账期天数"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="银行信息">
              <el-input
                v-model="formData.bankInfo"
                type="textarea"
                :rows="3"
                placeholder="请输入银行账户信息"
              />
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="其他信息" name="other">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="行业类型">
                  <el-input v-model="formData.industry" placeholder="请输入行业类型" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="公司规模">
                  <el-select v-model="formData.companySize" placeholder="请选择公司规模">
                    <el-option label="1-50人" value="small" />
                    <el-option label="51-200人" value="medium" />
                    <el-option label="201-1000人" value="large" />
                    <el-option label="1000人以上" value="enterprise" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户来源">
                  <el-select v-model="formData.source" placeholder="请选择客户来源">
                    <el-option label="网络推广" value="online" />
                    <el-option label="电话营销" value="phone" />
                    <el-option label="客户推荐" value="referral" />
                    <el-option label="展会" value="exhibition" />
                    <el-option label="其他" value="other" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="负责销售">
                  <el-select v-model="formData.salesperson" placeholder="请选择负责销售">
                    <el-option label="张三" value="张三" />
                    <el-option label="李四" value="李四" />
                    <el-option label="王五" value="王五" />
                    <el-option label="赵六" value="赵六" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="备注">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="客户详情" width="1000px">
      <div class="customer-detail" v-if="currentCustomer">
        <el-tabs>
          <el-tab-pane label="基本信息">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="客户编码">{{ currentCustomer.customerCode }}</el-descriptions-item>
              <el-descriptions-item label="客户名称">{{ currentCustomer.customerName }}</el-descriptions-item>
              <el-descriptions-item label="客户类型">
                <el-tag :type="getCustomerTypeColor(currentCustomer.customerType)" size="small">
                  {{ getCustomerTypeText(currentCustomer.customerType) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="联系人">{{ currentCustomer.contactPerson }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ currentCustomer.contactPhone }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{ currentCustomer.email }}</el-descriptions-item>
              <el-descriptions-item label="所在地区">{{ currentCustomer.region }}</el-descriptions-item>
              <el-descriptions-item label="详细地址">{{ currentCustomer.address || '无' }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ currentCustomer.createTime }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="getStatusColor(currentCustomer.status)" size="small">
                  {{ getStatusText(currentCustomer.status) }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          
          <el-tab-pane label="信用信息">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="信用等级">
                <el-tag :type="getCreditLevelColor(currentCustomer.creditLevel)" size="small">
                  {{ currentCustomer.creditLevel }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="信用额度">
                <span class="amount-text">¥{{ currentCustomer.creditLimit?.toLocaleString() }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="付款方式">{{ currentCustomer.paymentMethod || '无' }}</el-descriptions-item>
              <el-descriptions-item label="账期天数">{{ currentCustomer.paymentDays || 0 }}天</el-descriptions-item>
              <el-descriptions-item label="银行信息" :span="2">{{ currentCustomer.bankInfo || '无' }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          
          <el-tab-pane label="交易统计">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单总数">{{ currentCustomer.totalOrders }}</el-descriptions-item>
              <el-descriptions-item label="累计金额">
                <span class="amount-text">¥{{ currentCustomer.totalAmount?.toLocaleString() }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="最近订单">{{ currentCustomer.lastOrderDate || '无' }}</el-descriptions-item>
              <el-descriptions-item label="平均订单金额">
                <span class="amount-text">¥{{ currentCustomer.avgOrderAmount?.toLocaleString() || 0 }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 信用调整对话框 -->
    <el-dialog v-model="creditDialogVisible" title="调整信用" width="500px">
      <el-form :model="creditForm" label-width="100px">
        <el-form-item label="信用等级">
          <el-select v-model="creditForm.creditLevel" placeholder="请选择信用等级">
            <el-option label="AAA" value="AAA" />
            <el-option label="AA" value="AA" />
            <el-option label="A" value="A" />
            <el-option label="BBB" value="BBB" />
            <el-option label="BB" value="BB" />
            <el-option label="B" value="B" />
            <el-option label="C" value="C" />
          </el-select>
        </el-form-item>
        <el-form-item label="信用额度">
          <el-input-number
            v-model="creditForm.creditLimit"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="调整原因">
          <el-input
            v-model="creditForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入调整原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="creditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreditSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, View, Edit, ArrowDown } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const creditDialogVisible = ref(false)
const dialogTitle = ref('')
const activeTab = ref('basic')
const currentCustomer = ref(null)
const formRef = ref(null)
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  customerName: '',
  customerType: '',
  creditLevel: '',
  status: '',
  region: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 表单数据
const formData = reactive({
  id: null,
  customerName: '',
  customerType: 'enterprise',
  contactPerson: '',
  contactPhone: '',
  email: '',
  fax: '',
  region: '',
  address: '',
  creditLevel: 'A',
  creditLimit: 0,
  paymentMethod: 'transfer',
  paymentDays: 30,
  bankInfo: '',
  industry: '',
  companySize: 'medium',
  source: 'online',
  salesperson: '',
  remark: ''
})

// 信用调整表单
const creditForm = reactive({
  creditLevel: '',
  creditLimit: 0,
  reason: ''
})

// 表单验证规则
const formRules = {
  customerName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  customerType: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  region: [{ required: true, message: '请输入所在地区', trigger: 'blur' }],
  creditLevel: [{ required: true, message: '请选择信用等级', trigger: 'change' }],
  creditLimit: [{ required: true, message: '请输入信用额度', trigger: 'blur' }]
}

// 模拟数据
const mockData = [
  {
    id: 1,
    customerCode: 'C202401001',
    customerName: '北京科技有限公司',
    customerType: 'enterprise',
    contactPerson: '张经理',
    contactPhone: '13800138001',
    email: 'zhang@bjtech.com',
    region: '北京市',
    address: '北京市海淀区中关村大街1号',
    creditLevel: 'AAA',
    creditLimit: 1000000,
    paymentMethod: 'monthly',
    paymentDays: 30,
    bankInfo: '中国银行北京分行 1234567890',
    industry: '信息技术',
    companySize: 'large',
    source: 'referral',
    salesperson: '张三',
    totalOrders: 25,
    totalAmount: 2500000,
    lastOrderDate: '2024-01-20',
    avgOrderAmount: 100000,
    status: 'active',
    createTime: '2023-06-15 10:30:00',
    remark: '重要客户，优质合作伙伴'
  },
  {
    id: 2,
    customerCode: 'C202401002',
    customerName: '上海贸易集团',
    customerType: 'enterprise',
    contactPerson: '李总监',
    contactPhone: '13800138002',
    email: 'li@shtrade.com',
    region: '上海市',
    address: '上海市浦东新区陆家嘴金融区',
    creditLevel: 'AA',
    creditLimit: 800000,
    paymentMethod: 'transfer',
    paymentDays: 15,
    bankInfo: '工商银行上海分行 2345678901',
    industry: '贸易',
    companySize: 'enterprise',
    source: 'online',
    salesperson: '李四',
    totalOrders: 18,
    totalAmount: 1800000,
    lastOrderDate: '2024-01-18',
    avgOrderAmount: 100000,
    status: 'active',
    createTime: '2023-08-20 14:20:00',
    remark: '长期合作客户'
  },
  {
    id: 3,
    customerCode: 'C202401003',
    customerName: '深圳创新企业',
    customerType: 'enterprise',
    contactPerson: '王主管',
    contactPhone: '13800138003',
    email: 'wang@szinno.com',
    region: '深圳市',
    address: '深圳市南山区科技园',
    creditLevel: 'A',
    creditLimit: 500000,
    paymentMethod: 'credit',
    paymentDays: 45,
    bankInfo: '招商银行深圳分行 3456789012',
    industry: '制造业',
    companySize: 'medium',
    source: 'exhibition',
    salesperson: '王五',
    totalOrders: 12,
    totalAmount: 960000,
    lastOrderDate: '2024-01-15',
    avgOrderAmount: 80000,
    status: 'active',
    createTime: '2023-09-10 09:15:00',
    remark: '新兴客户，发展潜力大'
  },
  {
    id: 4,
    customerCode: 'C202401004',
    customerName: '广州制造公司',
    customerType: 'enterprise',
    contactPerson: '赵部长',
    contactPhone: '13800138004',
    email: 'zhao@gzmfg.com',
    region: '广州市',
    address: '广州市天河区珠江新城',
    creditLevel: 'BBB',
    creditLimit: 300000,
    paymentMethod: 'check',
    paymentDays: 60,
    bankInfo: '建设银行广州分行 4567890123',
    industry: '制造业',
    companySize: 'medium',
    source: 'phone',
    salesperson: '赵六',
    totalOrders: 8,
    totalAmount: 480000,
    lastOrderDate: '2024-01-10',
    avgOrderAmount: 60000,
    status: 'suspended',
    createTime: '2023-10-05 16:45:00',
    remark: '付款较慢，需要关注'
  },
  {
    id: 5,
    customerCode: 'C202401005',
    customerName: '杭州电商平台',
    customerType: 'enterprise',
    contactPerson: '钱经理',
    contactPhone: '13800138005',
    email: 'qian@hzecom.com',
    region: '杭州市',
    address: '杭州市西湖区文三路',
    creditLevel: 'AA',
    creditLimit: 600000,
    paymentMethod: 'transfer',
    paymentDays: 20,
    bankInfo: '浙商银行杭州分行 5678901234',
    industry: '电子商务',
    companySize: 'large',
    source: 'online',
    salesperson: '钱七',
    totalOrders: 20,
    totalAmount: 1600000,
    lastOrderDate: '2024-01-22',
    avgOrderAmount: 80000,
    status: 'active',
    createTime: '2023-07-12 11:30:00',
    remark: '电商平台，订单频繁'
  }
]

// 辅助方法
const getCustomerTypeColor = (type) => {
  const colorMap = {
    enterprise: 'primary',
    individual: 'success',
    government: 'warning',
    nonprofit: 'info'
  }
  return colorMap[type] || ''
}

const getCustomerTypeText = (type) => {
  const textMap = {
    enterprise: '企业客户',
    individual: '个人客户',
    government: '政府机构',
    nonprofit: '非营利组织'
  }
  return textMap[type] || type
}

const getCreditLevelColor = (level) => {
  const colorMap = {
    AAA: 'success',
    AA: 'success',
    A: 'primary',
    BBB: 'warning',
    BB: 'warning',
    B: 'danger',
    C: 'danger'
  }
  return colorMap[level] || ''
}

const getStatusColor = (status) => {
  const colorMap = {
    active: 'success',
    suspended: 'warning',
    blacklist: 'danger'
  }
  return colorMap[status] || ''
}

const getStatusText = (status) => {
  const textMap = {
    active: '正常',
    suspended: '暂停',
    blacklist: '黑名单'
  }
  return textMap[status] || status
}

// 事件处理方法
const handleAdd = () => {
  dialogTitle.value = '新增客户'
  activeTab.value = 'basic'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑客户'
  activeTab.value = 'basic'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleView = (row) => {
  currentCustomer.value = row
  viewDialogVisible.value = true
}

const handleCommand = async (command) => {
  const { action, row } = command
  
  try {
    switch (action) {
      case 'suspend':
        await ElMessageBox.confirm('确认暂停与该客户的合作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        row.status = 'suspended'
        ElMessage.success('客户状态已更新')
        break
      case 'activate':
        await ElMessageBox.confirm('确认恢复与该客户的合作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        row.status = 'active'
        ElMessage.success('客户状态已更新')
        break
      case 'blacklist':
        await ElMessageBox.confirm('确认将该客户加入黑名单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        row.status = 'blacklist'
        ElMessage.success('客户已加入黑名单')
        break
      case 'credit':
        creditForm.creditLevel = row.creditLevel
        creditForm.creditLimit = row.creditLimit
        creditForm.reason = ''
        currentCustomer.value = row
        creditDialogVisible.value = true
        break
      case 'orders':
        ElMessage.info('跳转到订单管理页面查看该客户的所有订单')
        break
    }
  } catch {
    // 用户取消操作
  }
}

const handleCreditSubmit = () => {
  if (currentCustomer.value) {
    currentCustomer.value.creditLevel = creditForm.creditLevel
    currentCustomer.value.creditLimit = creditForm.creditLimit
    ElMessage.success('信用信息已更新')
    creditDialogVisible.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    customerName: '',
    customerType: '',
    creditLevel: '',
    status: '',
    region: ''
  })
  handleSearch()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (formData.id) {
      // 编辑
      const index = tableData.value.findIndex(item => item.id === formData.id)
      if (index !== -1) {
        Object.assign(tableData.value[index], {
          ...formData,
          customerCode: tableData.value[index].customerCode,
          createTime: tableData.value[index].createTime
        })
      }
      ElMessage.success('客户信息更新成功')
    } else {
      // 新增
      const newCustomer = {
        ...formData,
        id: Date.now(),
        customerCode: `C${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(tableData.value.length + 1).padStart(3, '0')}`,
        totalOrders: 0,
        totalAmount: 0,
        lastOrderDate: null,
        avgOrderAmount: 0,
        status: 'active',
        createTime: new Date().toLocaleString('zh-CN')
      }
      tableData.value.unshift(newCustomer)
      pagination.total++
      ElMessage.success('客户创建成功')
    }
    
    dialogVisible.value = false
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    customerName: '',
    customerType: 'enterprise',
    contactPerson: '',
    contactPhone: '',
    email: '',
    fax: '',
    region: '',
    address: '',
    creditLevel: 'A',
    creditLimit: 0,
    paymentMethod: 'transfer',
    paymentDays: 30,
    bankInfo: '',
    industry: '',
    companySize: 'medium',
    source: 'online',
    salesperson: '',
    remark: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const loadData = () => {
  loading.value = true
  
  // 模拟API调用
  setTimeout(() => {
    let filteredData = [...mockData]
    
    // 应用搜索过滤
    if (searchForm.customerName) {
      filteredData = filteredData.filter(item => 
        item.customerName.toLowerCase().includes(searchForm.customerName.toLowerCase())
      )
    }
    if (searchForm.customerType) {
      filteredData = filteredData.filter(item => item.customerType === searchForm.customerType)
    }
    if (searchForm.creditLevel) {
      filteredData = filteredData.filter(item => item.creditLevel === searchForm.creditLevel)
    }
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }
    if (searchForm.region) {
      filteredData = filteredData.filter(item => 
        item.region.toLowerCase().includes(searchForm.region.toLowerCase())
      )
    }
    
    pagination.total = filteredData.length
    
    // 分页处理
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    tableData.value = filteredData.slice(start, end)
    
    loading.value = false
  }, 500)
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.customer-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.amount-text {
  color: #e6a23c;
  font-weight: bold;
}

.customer-form .el-form-item {
  margin-bottom: 20px;
}

.customer-detail {
  margin: 20px 0;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .customer-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    display: block;
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .el-table {
    font-size: 12px;
  }
}
</style>